import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
const Parent = () => {
  const input = useRef(null);
  const child = useRef(null); // react-dom.development.js:86 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
  console.log(input.current); // null  🚩 不要在渲染期间读取 ref
  console.log(child.current); //
  useEffect(() => {
    // ✅ 你可以在 effects 中读取和写入 ref
    console.log(input.current);
    console.log(child.current);
  });
  // function handleClick() {
  //   // ✅ 你可以在事件处理程序中读取和写入 ref
  //   console.log(input.current);
  //   console.log(child.current);
  // }
  return (
    <div>
      <div ref={input}>
        <input />
      </div>
      <Child ref={child} />
    </div>
  );
};

const Child = forwardRef(ref => {
  useImperativeHandle(
    ref,
    () => {
      return {
        a: 1,
        b: 2
      };
    },
    []
  );
  return <div ref={ref}>Child</div>;
});

Child.displayName = 'Child';

export default Parent;
